package com.chinawayltd.ews.sample.service.basicInfo.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.chinawayltd.ews.sample.mapper.TLogMapper;
import com.chinawayltd.ews.sample.mapper.TShiftMapper;
import com.chinawayltd.ews.sample.mapper.basicInfo.ShiftExtendMapper;
import com.chinawayltd.ews.sample.model.TLog;
import com.chinawayltd.ews.sample.model.TShift;
import com.chinawayltd.ews.sample.model.basicInfo.ShiftVO;
import com.chinawayltd.ews.sample.service.base.impl.BaseServiceImpl;
import com.chinawayltd.ews.sample.service.basicInfo.ShiftService;
import com.chinawayltd.ews.sample.util.PageData;
import com.chinawayltd.ews.sample.util.excel.ExcelObjModel;
import com.chinawayltd.ews.sample.util.excel.ExportCloumsModel;
import com.chinawayltd.ews.sample.web.query.ShiftGirdQuery;

/**
 * @program: greeProject
 * @description 班次管理service实现类
 * @author: chenxin
 * @create: 2018年4月12日 下午4:08:01
 */
@Service
public class ShiftServiceImpl extends BaseServiceImpl implements ShiftService {
	private static final SimpleDateFormat HHMM = new SimpleDateFormat("HH:mm");
	private static final String tableName = "T_SHIFT";

	@Autowired
	TShiftMapper tShiftMapper;

	@Autowired
	ShiftExtendMapper shiftExtendMapper;

	@Autowired
	private TLogMapper tLogMapper;

	@Override
	public List<ShiftVO> listShiftByPage(ShiftGirdQuery queryParam) {
		return shiftExtendMapper.listShiftByPage(queryParam);
	}

	@Override
	public TShift selectTShift(Long id) throws Exception{
		if(id == null || id <= 0){
            throw new RuntimeException("id不能为空或者少于等于0！");
        }
		return tShiftMapper.selectByPrimaryKey(id);
	}

	@Override
	public int addTShift(TShift tShift) {
		Date date = new Date();
		tShift.setCreateTime(date);
		tShift.setUpdateTime(date);
		int result = shiftExtendMapper.insert(tShift);
		if(result >0){
    		TLog log = new TLog();
    		log.setDataId(tShift.getId());
    		log.setTableName(tableName);
    		log.setOperationUser(getCurrentUser().getRealname());
    		log.setOperationType(1);
    		log.setCreateTime(date);
    		log.setUpdateTime(date);
    		tLogMapper.insert(log);
        }
		return result;
	}

	@Override
	public int updateTShift(TShift tShift) {
		Date date = new Date();
		tShift.setUpdateTime(date);
		int result = tShiftMapper.updateByPrimaryKeySelective(tShift);
		if(result >0){
    		TLog log = new TLog();
    		log.setDataId(tShift.getId());
    		log.setTableName(tableName);
    		log.setOperationUser(getCurrentUser().getRealname());
    		log.setOperationType(2);
    		log.setCreateTime(date);
    		log.setUpdateTime(date);
    		tLogMapper.insert(log);
        }
		return result;
	}

	@Override
	public int deleteTShift(long id) {
		return tShiftMapper.deleteByPrimaryKey(id);
	}

	@Override
	public List<TShift> listShiftByName(Long shiftId, String shiftName) {
		Map<String, Object> map = new HashMap<>();
		map.put("shiftId", shiftId);
		map.put("shiftName", shiftName);
		return shiftExtendMapper.listShiftByName(map);
	}

	@Override
	public List<TShift> getShiftByNameAndId(Long shiftId, String shiftName) {
		Map<String, Object> map = new HashMap<>();
		map.put("shiftId", shiftId);
		map.put("shiftName", shiftName);
		return shiftExtendMapper.getShiftByNameAndId(map);
	}

	@Override
	@Transactional
	public int deletesByIds(String[] ids) {
		return shiftExtendMapper.deleteAll(ids);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.chinawayltd.ews.sample.service.basicInfo.ShiftService#insertList(java
	 * .util.List)
	 */
	@Override
	@Transactional
	public ExcelObjModel insertList(List<PageData> list) throws Exception {
		ExcelObjModel model = new ExcelObjModel();
		List<Object> mapList = new ArrayList<>();
		model.setCode(0); // 0没添加1添加成功，否则有添加不成功的
		int result = 0;
		Date now = new Date();

		// 遍历读取的Excel数据，判断数据的正确性
		for (PageData pd : list) {
			try {
				TShift tShift = new TShift();
				String shiftName = pd.getString("var0");// 班次名称
				tShift.setShiftName(shiftName);
				String shiftType = pd.getString("var1");// 班次类型
				if (StringUtils.isNoneBlank(shiftType)) {
					switch (shiftType) {
					case "白班":
						tShift.setShiftType((byte) 0);
						break;
					case "晚班":
						tShift.setShiftType((byte) 1);
						break;
					}
				}
				String timeQuantum = pd.getString("var2");// 班次时间段
				String[] time = null;
				if (StringUtils.isNoneBlank(timeQuantum)) {
					time = timeQuantum.split("-");
					if (time.length == 2) {
						tShift.setBigTime(HHMM.format(HHMM.parse(time[0])));
						tShift.setEndTime(HHMM.format(HHMM.parse(time[1])));
					}
				}
				// 将对象转化为map，判断是否为空
				Map<String, Object> map = com.chinawayltd.ews.sample.util.MapUtils.objectToMap(tShift);
				if (StringUtils.isBlank(shiftName) || StringUtils.isBlank(shiftType)) {
					map.put("describe", "填写的字段不能为空");
					map.put("timeQuantum", timeQuantum);
					map.put("shiftTypeName", shiftType);
					mapList.add(map);
					continue;
				}
				if (!"白班".equals(shiftType) && !"晚班".equals(shiftType)) {
					map.put("describe", "填写的班次为白班或晚班");
					map.put("timeQuantum", timeQuantum);
					map.put("shiftTypeName", shiftType);
					mapList.add(map);
					continue;
				}
				// 判断班次名称是否重复
				List<TShift> shiftByNameAndId = getShiftByNameAndId(null, shiftName);
				if (shiftByNameAndId.size() > 0) {
					map.put("describe", "填写的名称重复");
					map.put("timeQuantum", timeQuantum);
					map.put("shiftTypeName", shiftType);
					mapList.add(map);
					continue;
				}
				if (time != null) {
					if (time.length == 2) {
						if (StringUtils.isBlank(time[0]) || StringUtils.isBlank(time[1])) {
							map.put("describe", "填写的时间段格式有误");
							map.put("timeQuantum", timeQuantum);
							map.put("shiftTypeName", shiftType);
							mapList.add(map);
							continue;
						}
						if (time[1].equals("00:00") || time[1].equals("0:00")) {
							map.put("describe", "结束时间不能为00:00");
							map.put("timeQuantum", timeQuantum);
							map.put("shiftTypeName", shiftType);
							mapList.add(map);
							continue;
						}
						/*if (HHMM.parse(time[0]).getTime() > HHMM.parse(time[1]).getTime()) {
							map.put("describe", "开始时间必须小于结束时间");
							map.put("timeQuantum", timeQuantum);
							map.put("shiftTypeName", shiftType);
							mapList.add(map);
							continue;
						}*/
					} else {
						map.put("describe", "填写的时间段格式有误");
						map.put("timeQuantum", timeQuantum);
						map.put("shiftTypeName", shiftType);
						mapList.add(map);
						continue;
					}
				} else {
					map.put("describe", "填写的时间段不能为空");
					map.put("timeQuantum", timeQuantum);
					map.put("shiftTypeName", shiftType);
					mapList.add(map);
					continue;
				}

				boolean judgeTimeConflict = judgeTimeConflict(tShift);
				if (judgeTimeConflict) {
					map.put("describe", "班次时间冲突");
					map.put("timeQuantum", timeQuantum);
					map.put("shiftTypeName", shiftType);
					mapList.add(map);
					continue;
				}

				tShift.setCreateTime(now);
				tShift.setUpdateTime(now);
				result = shiftExtendMapper.insert(tShift);
				map.put("describe", "导入成功");
				map.put("timeQuantum", timeQuantum);
				map.put("shiftTypeName", shiftType);
				mapList.add(map);
				if (result > 0) {
					TLog log = new TLog();
					log.setDataId(tShift.getId());
					log.setTableName(tableName);
					log.setOperationUser(getCurrentUser().getRealname());
					log.setOperationType(1);
					log.setCreateTime(now);
					log.setUpdateTime(now);
					tLogMapper.insert(log);
				}
				model.setCode(result);
			} catch (Exception e) {
				e.printStackTrace();
				model.setCode(0);
				Map<String, Object> exceptionMap = new HashMap<>();
				exceptionMap.put("shiftName", pd.getString("var0"));
				exceptionMap.put("shiftTypeName", pd.getString("var1"));
				exceptionMap.put("timeQuantum", pd.getString("var2"));
				exceptionMap.put("describe", "数据异常，导入失败");
				mapList.add(exceptionMap);
			}

		}
		model.setList(mapList);
		List<ExportCloumsModel> cloums = new ArrayList<>();
		if (mapList.size() > 0) {
			cloums.add(new ExportCloumsModel("班次名称", "shiftName"));
			cloums.add(new ExportCloumsModel("班次类型", "shiftTypeName"));
			cloums.add(new ExportCloumsModel("班次时间段", "timeQuantum"));
			cloums.add(new ExportCloumsModel("导入描述", "describe"));
		}
		model.setCloums(cloums);
		return model;
	}

	@Override
	public boolean judgeTimeConflict(TShift shift) {
		try {
			String bigTime_ = shift.getBigTime();
			String endTime_ = shift.getEndTime();
			String id_ = shift.getId() != null ? shift.getId().toString() : "";
			List<Map<String, Object>> shiftMapList = shiftExtendMapper.judgeTimeConflict(id_);
			if (shiftMapList.size() > 0) {
				for (Map<String, Object> shiftMap : shiftMapList) {
					String bigTime = MapUtils.getString(shiftMap, "big_time");
					String endTime = MapUtils.getString(shiftMap, "end_time");
					Date bigDate = HHMM.parse(bigTime);
					Date endDate = HHMM.parse(endTime);
					Date bigDate_ = HHMM.parse(bigTime_);
					Date endDate_ = HHMM.parse(endTime_);
					if (bigDate_.compareTo(endDate_) <= 0) {// 传参的时间是正常的，开始时间小于结束时间
						boolean flag = this.executeTimeJudgment(bigDate_, endDate_, bigDate, endDate);
						if (flag) {
							return true;
						}
					} else if (bigDate_.compareTo(endDate_) > 0) {// 传参时间有过度，如18:00-06:00
						// 先用24小时来换算,如18:00-23:59 00:00-06:00
						Date endDateTran_ = HHMM.parse("23:59");
						boolean flag_1 = this.executeTimeJudgment(bigDate_, endDateTran_, bigDate, endDate);
						Date bigDateTran_ = HHMM.parse("00:00");
						boolean flag_2 = this.executeTimeJudgment(bigDateTran_, endDate_, bigDate, endDate);
						if (flag_1 || flag_2) {
							return true;
						}
					}
				}
			}
		} catch (ParseException e) {
			e.printStackTrace();
			return true;// 存在冲突
		}
		return false;
	}

	/**
	 * @author Fay
	 * @date 2018年5月23日 上午11:36:30
	 * @param bigDate_ 传参过来的开始时间
	 * @param endDate_ 传参过来的结束时间
	 * @param bigDate 查数据库的开始时间
	 * @param endDate 查数据库的结束时间
	 * @return true 有冲突 false 无冲突
	 */
	private boolean JudgeDateWhetherOrNotConflict(Date bigDate_, Date endDate_, Date bigDate, Date endDate) {
		if ((bigDate_.compareTo(bigDate) > 0 || bigDate_.compareTo(bigDate) == 0) && bigDate_.compareTo(endDate) < 0) {
			return true;
		} else if ((endDate_.compareTo(endDate) < 0 || endDate_.compareTo(endDate) == 0) && endDate_.compareTo(bigDate) > 0) {
			return true;
		}
		return false;
	}

	/**
	 * @author Fay
	 * @date 2018年5月23日 上午11:48:44
	 * @param bigDate_ 传参过来的开始时间
	 * @param endDate_ 传参过来的结束时间
	 * @param bigDate 查数据库的开始时间
	 * @param endDate 查数据库的结束时间
	 * @return true 有冲突 false 无冲突
	 * @throws ParseException
	 */
	private boolean executeTimeJudgment(Date bigDate_, Date endDate_, Date bigDate, Date endDate)
			throws ParseException {
		if (bigDate.compareTo(endDate) < 0) {// 正常开始时间是小于结束时间，判断传入的参数是否与此时间段相交
			return this.JudgeDateWhetherOrNotConflict(bigDate_, endDate_, bigDate, endDate);
		} else if (bigDate.compareTo(endDate) > 0) {// 如果查数据库时间为18:00-06:00
			// 先用24小时来换算,如18:00-23:59 00:00-06:00
			Date endDateTran = HHMM.parse("23:59");
			boolean flag_1 = this.JudgeDateWhetherOrNotConflict(bigDate_, endDate_, bigDate, endDateTran);
			Date bigDateTran = HHMM.parse("00:00");
			boolean flag_2 = this.JudgeDateWhetherOrNotConflict(bigDate_, endDate_, bigDateTran, endDate);
			if (flag_1 || flag_2) {
				return true;
			}
		}
		return false;
	}

	@Override
	public List<Map<String, Object>> exportGirdData(ShiftGirdQuery queryParam) {
		return shiftExtendMapper.listShiftToMap(queryParam);
	}

}
